/**
                     GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.
 
 */
package com.pic.text;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.AbstractHttpEntity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class OCR extends BaseHttpClient {

	private static final String TAG = PicText.class.getSimpleName();

	private Bitmap bitmap = null;
	private Handler handler;
	File file = null;

	public OCR(String endpoint, int timeout, File fileIP) {
		super(endpoint, timeout);

		try {
	
			file = fileIP;

			bitmap = BitmapFactory.decodeStream(new BufferedInputStream(
					new FileInputStream(file)), null, null); // .decodeStream(stream,
			// null, null);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("STACK TRACE :-" + e);
		
		}
	}

	public String run() {

		String ocredText = null;
		try {

			if (bitmap != null) {
				bitmap = convertToGrayscale(bitmap);
				ocredText = sendOcrRequest(bitmap);
				Log.d(TAG, "OCR result: " + ocredText);

				return ocredText;

			}
		} catch (Exception e) {
			Log.e("TAG", "OCR failed", e);
			Message msg = handler.obtainMessage(2, 0, 0);
			handler.sendMessage(msg);
		}
		return ocredText;

	}

	public String sendOcrRequest(Bitmap img) throws IOException {
		Log.i(TAG, "Sending OCR request to " + url);
		HttpPost post = createPost(img);
		
		BufferedReader reader = null;
		
		try {
			HttpResponse resp =  httpClient.execute(post);
			
			reader = new BufferedReader(new InputStreamReader(resp.getEntity()
					.getContent(), "utf-8"));

			String status = reader.readLine();
			if (status.length() != 0) {
				status += readAllLines(reader);
				//throw new RuntimeException("WeOCR failed. Status: " + status);
			}
						
			return readAllLines(reader);
			 
			} catch (HttpResponseException re) {
			Log.e(TAG, "HTTP response exception", re);
			throw new RuntimeException("HTTP request failed. Status: "
					+ re.getStatusCode());
		} finally {
			if (reader != null) {
				reader.close();
			} 
		}
	}
	
	protected String readAllLines(BufferedReader reader) throws IOException {
		StringBuffer buff = new StringBuffer();
		String line = null;

		while ((line = reader.readLine()) != null) {
			buff.append(line);
			buff.append('\n');
		}

		return buff.toString().trim();
	}

	protected HttpPost createPost(Object param) throws IOException {
		Log.i(TAG, "Creating Post OCR ");
		HttpPost post = new HttpPost(url);
		Log.i(TAG, "return Post OCR ");
		post.setEntity(createEntity(param));

		return post;
	}

	protected AbstractHttpEntity createEntity(Object param) throws IOException {
		return new OcrFormEntity((Bitmap) param);
	}
	
	private Bitmap convertToGrayscale(Bitmap bitmap) {
        ColorMatrix colorMatrix = new ColorMatrix();
        colorMatrix.setSaturation(0);
        Paint paint = new Paint();
        ColorMatrixColorFilter cmcf = new ColorMatrixColorFilter(colorMatrix);
        paint.setColorFilter(cmcf);

        Bitmap result = Bitmap.createBitmap(bitmap.getWidth(), bitmap
                .getHeight(), Bitmap.Config.RGB_565);

        Canvas drawingCanvas = new Canvas(result);
        Rect src = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        Rect dst = new Rect(src);
        drawingCanvas.drawBitmap(bitmap, src, dst, paint);

        return result;
    }
}
